package com.fly.show.web;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fly.locks.distributed.memcache.MemcachedLockClient;
import com.fly.locks.distributed.memcache.MemcachedLockThread;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "测试分布式锁")
@RestController
public class TestController
{
    @Autowired
    MemcachedLockClient memcachedLock;
    
    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    
    /**
     * 初始化
     */
    @PostConstruct
    public void init()
    {
        // ****** 重要，先释放锁，防止程序被异常终止，锁未释放 *****
        memcachedLock.remove("key");
    }
    
    @ApiOperation("测试MemcachedLock")
    @GetMapping("/tm")
    public void testMemcachedLock()
        throws InterruptedException
    {
        Runnable runnable = new MemcachedLockThread(memcachedLock);
        int i = 0;
        while (i++ < 100)
        {
            TimeUnit.MILLISECONDS.sleep(RandomUtils.nextInt(100, 1000));
            cachedThreadPool.execute(runnable);
        }
    }
}
